package com.jarveis.frame.io;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
 * @desc FTP传输
 * @author liuguojun
 * @date 2015-08-27
 */
public class SFtpTransfer implements NetTransfer {

	private static final Logger logger = Logger.getLogger(SFtpTransfer.class);

	private String host; // 主机
	private int port = 0; // 端口
	private String user; // 用户
	private String password; // 密码
	private JSch client = new JSch();
	private Session session = null;
	private ChannelSftp channel;

	public SFtpTransfer(String host, int port, String user, String password) {
		this.host = host;
		this.port = port;
		this.user = user;
		this.password = password;
	}

	public boolean connect() throws Exception {
		session = client.getSession(user, host, port);
		if (session == null) {
			logger.info("net error. --->" + host);
			return false;
		}

		// 设置登陆主机的密码
		session.setPassword(password);
		// 设置第一次登陆的时候提示，可选值：(ask | yes | no)
		session.setConfig("StrictHostKeyChecking", "no");
		// 设置登陆超时时间
		session.connect(30000);

		// 创建sftp通信通道
		Channel sftp = (Channel) session.openChannel("sftp");
		sftp.connect(1000);
		channel = (ChannelSftp) sftp;
		logger.info("logined sftp server. --->" + host);

		return true;
	}

	public boolean disconnect() throws IOException {
		if (channel != null) {
			channel.disconnect();
		}
		if (session != null) {
			session.disconnect();
		}

		return true;
	}

	public boolean download(String remote, String local) throws Exception {
		channel.get(remote, local);

		return true;
	}
	
	public byte[] download(String remote) throws Exception {
		return null;
	}

	public boolean upload(String local, String remote) throws Exception {
		File localFile = new File(local);
		if (localFile.isDirectory()) {
			return true;
		}

		// 对远程目录的处理
		String remoteFileName = remote;
		if (remote.contains("/")) {
			remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
			// 创建服务器远程目录结构，创建失败直接返回
			if (!CreateDirecroty(remote)) {
				return false;
			}
		}

		channel.put(local, remoteFileName);
		logger.info("upload file success. --->" + remote);
		return true;
	}
	
	public boolean upload(byte[] byteArr, String remote) throws Exception {
		return false;
	}

	public boolean CreateDirecroty(String remote) throws Exception {
		String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
		if (!directory.equals("/")) {
			// 如果远程目录不存在，则递归创建远程服务器目录
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
				// 切换到根目录
				channel.cd("/");
			} else {
				start = 0;
			}
			end = directory.indexOf("/", start);
			while (true) {
				String subDirectory = remote.substring(start, end);
				try {
					// 目录是否存在
					channel.cd(subDirectory);
				} catch (SftpException sex) {
					// 创建目录
					channel.mkdir(subDirectory);
					channel.cd(subDirectory);
					logger.info("create folder success. --->" + subDirectory);
				}
				start = end + 1;
				end = directory.indexOf("/", start);

				// 检查所有目录是否创建完毕
				if (end <= start) {
					break;
				}
			}
		}
		
		return true;
	}

	public boolean remove(String remote) throws Exception {
		return false;
	}
}
